package org.eclipse.core.databinding.observable.list;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

import java.util.ArrayList;

/**
 * List support single selection
 */
public class SingleSelectionList<E> extends WritableList<E> implements SingleSelection<E>{
  transient protected PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);

  private int selectedIndex = -1;

  public SingleSelectionList(Class elementType) {
    super(new ArrayList(), elementType);
  }

  public boolean add(E e) {
    boolean ret = super.add(e);
    
    if (selectedIndex == -1){
      setSelectedIndex(0);
    }
    return ret;
  }
  public void add(int index, E e) {
    super.add(index, e);

    if (selectedIndex == -1){
      setSelectedIndex(0);
    }
  }

  public E remove(int index) {
    E ret = super.remove(index);
    if (this.size() == 0){
      setSelectedIndex(-1);
    }
    return ret;
  }
  public boolean remove(Object o) {
    boolean ret = super.remove(o);
    
    if (this.size() == 0){
      setSelectedIndex(-1);
    }
    return ret;
  }
  public void clear() {
    super.clear();
    setSelectedIndex(-1);
  }

  public void addPropertyChangeListener(PropertyChangeListener listener){
    changeSupport.addPropertyChangeListener(listener);
  }
  public void addPropertyChangeListener(String propName, PropertyChangeListener listener){
    changeSupport.addPropertyChangeListener(propName, listener);
  }
  public void removePropertyChangeListener(PropertyChangeListener listener){
    changeSupport.removePropertyChangeListener(listener);
  }
  public void removePropertyChangeListener(String propName, PropertyChangeListener listener){
    changeSupport.removePropertyChangeListener(propName, listener);
  }

  public E getSelected() {
    return selectedIndex == -1 ? null : this.get(selectedIndex);
  }

  public int getSelectedIndex() {
    return selectedIndex;
  }

  public void setSelectedIndex(int selectedIndex) {
    int oldSelectedIndex = this.selectedIndex;
    E oldSelected = null;
    if (this.selectedIndex >= 0){
      oldSelected = getSelected();
    }
    
    this.selectedIndex = selectedIndex;
    E newSelected = getSelected();

    changeSupport.firePropertyChange("selectedIndex", oldSelectedIndex, selectedIndex);
    changeSupport.firePropertyChange("selected", oldSelected, newSelected);
  }
}
